package com.crm.controller;


import com.crm.base.PageResult;
import com.crm.base.ResponseResult;
import com.crm.domain.dto.BusinessDto;
import com.crm.domain.entity.Business;
import com.crm.domain.vo.BusinessVo;
import com.crm.service.BusinessService;
import com.crm.service.IBusinessRecordService;
import com.crm.utils.BasicEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商机管理
 */
@Slf4j
@Api(tags = "商机管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/business")
public class BusinessController {

    private final BusinessService businessService;

    private final IBusinessRecordService iBusinessRecordService;


    /**
     * 分页查询客户信息
     *
     * @param businessDto
     * @return
     */
    @ApiOperation(value = "分页查询客户信息")
    @GetMapping("/list")
    public PageResult<List<BusinessVo>> page(BusinessDto businessDto) {
        PageResult<BusinessVo> pageResult = businessService.queryAll(businessDto);
        return PageResult.success(pageResult.getMsg(), pageResult.getRows(), pageResult.getTotal());
    }

    /**
     * 新增客户信息
     *
     * @param business
     * @return
     */
    @ApiOperation(value = "新增客户信息")
    @PostMapping
    public ResponseResult addInfo(@RequestBody Business business) {
        //根据手机号判断该用户是否已经存在,如果不存在则新增
        boolean exists = businessService.checkIfExistsByPhone(business.getPhone());
        if (exists) {
            return ResponseResult.error(BasicEnum.USER_ISEXIST);
        }
        // 新增用户信息
        businessService.add(business);
        return ResponseResult.success();
    }

    /**
     * 根据id查看客户信息
     * 跟进客户信息
     */
    @ApiOperation(value = "根据id查看客户信息")
    @GetMapping("/{id}")
    public ResponseResult<Business> selectById(@PathVariable("id") Long id) {
        Business business = businessService.getById(id);
        return ResponseResult.success(business);
    }

    /**
     *
     * 根据businessid查询客户沟通记录
     * @param businessId
     * @return
     */
    @GetMapping("/record/list")
    public ResponseResult<BusinessVo> getById(Long businessId) {
        List<Business> list = businessService.lambdaQuery().eq(Business::getId, businessId).list();
        return ResponseResult.success(list);
    }

    /**
     * 修改客户信息(保存)
     * id为null 手机号作为唯一标识
     */
    @ApiOperation(value = "根据id修改客户信息")
    @PostMapping("/record")
    public ResponseResult updateById(@RequestBody Business business ) {
        //修改用户信息 phone作为唯一标识
        businessService.lambdaUpdate().eq(Business::getPhone, business.getPhone()).update(business);
        //新增用户沟通记录到record表
        iBusinessRecordService.addInfo(business);
        return ResponseResult.success();
    }

}
